package com.abing.permissionsys.security.utils;

import com.abing.permissionsys.utils.RedisUtil;
import com.abing.permissionsys.security.security.JwtUser;
import com.abing.permissionsys.utils.StringUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;

@Component
public class JwtTokenUtil implements Serializable {

    private static final long serialVersionUID = -3301605591108950415L;

//    @Value("${jwt.secret}")
//    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 校验token是否正确
     * @param token 密钥
     * @return 是否正确
     */
    public boolean validateToken(String token, JwtUser jwtUser) {
        try {
//            Algorithm algorithm = Algorithm.HMAC256(jwtUser.getPassword());
//            JWTVerifier verifier = JWT.require(algorithm)
//                    .withClaim("username", jwtUser.getUsername())
//                    .build();
//            DecodedJWT jwt = verifier.verify(token);
//            return true;

            if (jwtUser==null){
                return false;
            }
            if (StringUtils.isEmpty(jwtUser.getUsername())){
                return false;
            }
            String userName= (String) redisUtil.getObject(token);
            if (StringUtils.isNotEmpty(userName)&&userName.equals(jwtUser.getUsername())){
                return true;
            }
            return false;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户名
     */
    public String getUsername(String token) {
        try {
//            DecodedJWT jwt = JWT.decode(token);
//            return jwt.getClaim("username").asString();


            String userName= (String) redisUtil.getObject(token);
            if (StringUtils.isNotEmpty(userName)){
                return userName;
            }
            return null;
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static String getTokenData(String token) {
        try {
            return JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,5min后过期
     * @param jwtUser 用户名
     * @return 加密的token
     */
    public String sign(JwtUser jwtUser) {
        try {
            Date date = new Date(System.currentTimeMillis()+expiration);
            Algorithm algorithm = Algorithm.HMAC256(jwtUser.getPassword());
            // 附带username信息
            String token= JWT.create()
                    .withClaim("username", jwtUser.getUsername())
                    .withExpiresAt(date)
                    .sign(algorithm);
            redisUtil.setObject(token,jwtUser.getUsername(),expiration);
            return token;
        } catch (Exception e){
            return null;
        }
    }
}

